"use client"

import { useState, useEffect } from "react"
import { useNavigate, useLocation } from "react-router-dom"
import { Menu, Spin } from "antd"
import { DashboardOutlined, TeamOutlined, ProjectOutlined, SettingOutlined } from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"

interface SidebarContentProps {
  collapsed: boolean
}

const SidebarContent = ({ collapsed }: SidebarContentProps) => {
  const navigate = useNavigate()
  const location = useLocation()
  const { departments, projects, loading } = useHosts()
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  const [openKeys, setOpenKeys] = useState<string[]>([])

  useEffect(() => {
    const pathSnippets = location.pathname.split("/").filter((i) => i)
    if (pathSnippets.length === 0) {
      setSelectedKeys(["dashboard"])
    } else if (pathSnippets[0] === "departments" && pathSnippets[1]) {
      setSelectedKeys([`department-${pathSnippets[1]}`])
      setOpenKeys((prev) => [...prev, "departments"])
    } else if (pathSnippets[0] === "projects" && pathSnippets[1]) {
      setSelectedKeys([`project-${pathSnippets[1]}`])
      setOpenKeys((prev) => [...prev, "projects"])
    } else if (pathSnippets[0] === "settings") {
      setSelectedKeys(["settings"])
    }
  }, [location.pathname])

  const handleMenuClick = (key: string) => {
    if (key === "dashboard") {
      navigate("/")
    } else if (key === "settings") {
      navigate("/settings")
    } else if (key.startsWith("department-")) {
      const departmentId = key.replace("department-", "")
      navigate(`/departments/${departmentId}`)
    } else if (key.startsWith("project-")) {
      const projectId = key.replace("project-", "")
      navigate(`/projects/${projectId}`)
    }
  }

  const handleOpenChange = (keys: string[]) => {
    setOpenKeys(keys)
  }

  if (loading) {
    return (
      <div style={{ padding: 24, textAlign: "center" }}>
        <Spin />
      </div>
    )
  }

  return (
    <Menu
      theme="dark"
      mode="inline"
      selectedKeys={selectedKeys}
      openKeys={collapsed ? [] : openKeys}
      onOpenChange={handleOpenChange}
      onClick={({ key }) => handleMenuClick(key)}
      items={[
        {
          key: "dashboard",
          icon: <DashboardOutlined />,
          label: "仪表盘",
        },
        {
          key: "departments",
          icon: <TeamOutlined />,
          label: "部门视图",
          children:
            departments.length > 0
              ? departments.map((dept) => ({
                  key: `department-${dept.id}`,
                  label: dept.name,
                }))
              : [{ key: "no-departments", label: "暂无部门", disabled: true }],
        },
        {
          key: "projects",
          icon: <ProjectOutlined />,
          label: "项目视图",
          children:
            projects.length > 0
              ? projects.map((project) => ({
                  key: `project-${project.id}`,
                  label: project.name,
                }))
              : [{ key: "no-projects", label: "暂无项目", disabled: true }],
        },
        {
          key: "settings",
          icon: <SettingOutlined />,
          label: "系统设置",
        },
      ]}
    />
  )
}

export default SidebarContent
